//! # 限流控制模块
//!
//! 提供企业级的限流控制解决方案，支持多种限流算法和灵活的限流策略。
//!
//! ## 核心功能
//!
//! * **多种限流算法** - 令牌桶、漏桶、固定窗口、滑动窗口
//! * **多维度限流** - 基于IP、用户、API、服务的限流控制
//! * **分布式限流** - 支持Redis等外部存储的分布式限流
//! * **动态配置** - 支持运行时调整限流参数
//! * **统计分析** - 详细的限流统计和分析报告
//!
//! ## 使用示例
//!
//! ```rust
//! use rustcloud_gateway::rate_limit::*;
//!
//! // 创建令牌桶限流器
//! let algorithm = TokenBucketAlgorithm::new(100, Duration::from_secs(60));
//! let strategy = IpBasedStrategy::new();
//! let limiter = RateLimiter::new(algorithm, strategy);
//!
//! // 检查请求是否允许
//! let context = RequestContext::from_request(&request);
//! let allowed = limiter.is_allowed(&context).await?;
//! ```

pub mod algorithms;
pub mod strategies;
pub mod storage;
pub mod middleware;

#[cfg(test)]
pub mod rate_limit_comprehensive_tests;

use async_trait::async_trait;
use axum::http::HeaderMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::IpAddr;
use std::time::{Duration, SystemTime};
use thiserror::Error;
use tracing::{debug, warn};

/// 限流错误类型
#[derive(Error, Debug)]
pub enum RateLimitError {
    #[error("限流超出限制")]
    LimitExceeded,
    
    #[error("存储错误: {0}")]
    StorageError(String),
    
    #[error("配置错误: {0}")]
    ConfigError(String),
    
    #[error("内部错误: {0}")]
    InternalError(String),
}

/// 限流结果类型
pub type RateLimitResult<T> = Result<T, RateLimitError>;

/// 限流算法类型
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RateLimitAlgorithmType {
    /// 令牌桶算法
    TokenBucket,
    /// 漏桶算法
    LeakyBucket,
    /// 固定窗口算法
    FixedWindow,
    /// 滑动窗口算法
    SlidingWindow,
    /// 滑动日志算法
    SlidingLog,
}

/// 限流策略类型
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RateLimitStrategyType {
    /// 基于IP地址
    IpBased,
    /// 基于用户ID
    UserBased,
    /// 基于API Key
    ApiKeyBased,
    /// 基于API路径
    PathBased,
    /// 基于服务名称
    ServiceBased,
    /// 组合策略
    Composite,
    /// 自定义策略
    Custom(String),
}

/// 请求上下文
///
/// 包含限流所需的请求信息，用于限流策略生成限流键。
#[derive(Debug, Clone)]
pub struct RequestContext {
    /// 客户端IP地址
    pub client_ip: Option<IpAddr>,
    /// 用户ID
    pub user_id: Option<String>,
    /// API Key
    pub api_key: Option<String>,
    /// 请求路径
    pub path: String,
    /// HTTP方法
    pub method: String,
    /// 目标服务
    pub service: Option<String>,
    /// 请求头
    pub headers: HeaderMap,
    /// 查询参数
    pub query_params: HashMap<String, String>,
    /// 请求时间戳
    pub timestamp: SystemTime,
    /// 自定义属性
    pub attributes: HashMap<String, String>,
}

impl RequestContext {
    /// 创建新的请求上下文
    pub fn new(path: String, method: String) -> Self {
        Self {
            client_ip: None,
            user_id: None,
            api_key: None,
            path,
            method,
            service: None,
            headers: HeaderMap::new(),
            query_params: HashMap::new(),
            timestamp: SystemTime::now(),
            attributes: HashMap::new(),
        }
    }

    /// 设置客户端IP
    pub fn with_client_ip(mut self, ip: IpAddr) -> Self {
        self.client_ip = Some(ip);
        self
    }

    /// 设置用户ID
    pub fn with_user_id(mut self, user_id: String) -> Self {
        self.user_id = Some(user_id);
        self
    }

    /// 设置API Key
    pub fn with_api_key(mut self, api_key: String) -> Self {
        self.api_key = Some(api_key);
        self
    }

    /// 设置目标服务
    pub fn with_service(mut self, service: String) -> Self {
        self.service = Some(service);
        self
    }

    /// 添加属性
    pub fn add_attribute(mut self, key: String, value: String) -> Self {
        self.attributes.insert(key, value);
        self
    }

    /// 获取属性
    pub fn get_attribute(&self, key: &str) -> Option<&String> {
        self.attributes.get(key)
    }

    /// 从请求头获取值
    pub fn get_header(&self, name: &str) -> Option<&str> {
        self.headers.get(name)?.to_str().ok()
    }

    /// 获取User-Agent
    pub fn get_user_agent(&self) -> Option<&str> {
        self.get_header("user-agent")
    }

    /// 获取Referer
    pub fn get_referer(&self) -> Option<&str> {
        self.get_header("referer")
    }
}

/// 限流配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// 限流算法类型
    pub algorithm: RateLimitAlgorithmType,
    /// 最大请求数
    pub max_requests: u32,
    /// 时间窗口
    pub window_duration: Duration,
    /// 突发容量（用于令牌桶）
    pub burst_capacity: Option<u32>,
    /// 补充速率（用于令牌桶，每秒补充的令牌数）
    pub refill_rate: Option<u32>,
    /// 是否启用
    pub enabled: bool,
    /// 阻塞行为
    pub block_behavior: BlockBehavior,
    /// 自定义参数
    pub custom_params: HashMap<String, String>,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            algorithm: RateLimitAlgorithmType::TokenBucket,
            max_requests: 100,
            window_duration: Duration::from_secs(60),
            burst_capacity: Some(10),
            refill_rate: Some(10),
            enabled: true,
            block_behavior: BlockBehavior::Reject,
            custom_params: HashMap::new(),
        }
    }
}

/// 阻塞行为
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlockBehavior {
    /// 直接拒绝
    Reject,
    /// 延迟处理
    Delay,
    /// 降级处理
    Fallback,
}

/// 限流结果
#[derive(Debug, Clone)]
pub struct RateLimitDecision {
    /// 是否允许请求
    pub allowed: bool,
    /// 剩余配额
    pub remaining: u32,
    /// 配额重置时间
    pub reset_time: SystemTime,
    /// 延迟时间（如果需要延迟）
    pub delay: Option<Duration>,
    /// 限流原因
    pub reason: Option<String>,
    /// 限流规则ID
    pub rule_id: Option<String>,
}

impl RateLimitDecision {
    /// 创建允许的决策
    pub fn allowed(remaining: u32, reset_time: SystemTime) -> Self {
        Self {
            allowed: true,
            remaining,
            reset_time,
            delay: None,
            reason: None,
            rule_id: None,
        }
    }

    /// 创建拒绝的决策
    pub fn rejected(reason: String, reset_time: SystemTime) -> Self {
        Self {
            allowed: false,
            remaining: 0,
            reset_time,
            delay: None,
            reason: Some(reason),
            rule_id: None,
        }
    }

    /// 创建延迟的决策
    pub fn delayed(delay: Duration, remaining: u32, reset_time: SystemTime) -> Self {
        Self {
            allowed: true,
            remaining,
            reset_time,
            delay: Some(delay),
            reason: None,
            rule_id: None,
        }
    }

    /// 设置规则ID
    pub fn with_rule_id(mut self, rule_id: String) -> Self {
        self.rule_id = Some(rule_id);
        self
    }
}

/// 限流算法trait
///
/// 定义了限流算法的核心接口，支持不同的限流算法实现。
#[async_trait]
pub trait RateLimitAlgorithm: Send + Sync {
    /// 检查是否允许请求
    ///
    /// # 参数
    /// * `key` - 限流键
    /// * `tokens` - 请求的令牌数量
    /// * `config` - 限流配置
    ///
    /// # 返回值
    /// * `Ok(RateLimitDecision)` - 限流决策结果
    /// * `Err(RateLimitError)` - 检查过程中出现错误
    async fn is_allowed(
        &self,
        key: &str,
        tokens: u32,
        config: &RateLimitConfig,
    ) -> RateLimitResult<RateLimitDecision>;

    /// 获取剩余配额
    async fn get_remaining(&self, key: &str, config: &RateLimitConfig) -> RateLimitResult<u32>;

    /// 重置限流状态
    async fn reset(&self, key: &str) -> RateLimitResult<()>;

    /// 获取算法类型
    fn get_algorithm_type(&self) -> RateLimitAlgorithmType;

    /// 获取算法名称
    fn get_algorithm_name(&self) -> &str;
}

/// 限流策略trait
///
/// 定义了如何从请求上下文生成限流键的接口。
#[async_trait]
pub trait RateLimitStrategy: Send + Sync {
    /// 生成限流键
    ///
    /// # 参数
    /// * `context` - 请求上下文
    ///
    /// # 返回值
    /// 限流键，用于标识不同的限流对象
    async fn get_key(&self, context: &RequestContext) -> String;

    /// 获取限流配置
    ///
    /// # 参数
    /// * `context` - 请求上下文
    ///
    /// # 返回值
    /// 适用于该请求的限流配置
    async fn get_config(&self, context: &RequestContext) -> RateLimitConfig;

    /// 获取策略类型
    fn get_strategy_type(&self) -> RateLimitStrategyType;

    /// 获取策略名称
    fn get_strategy_name(&self) -> &str;

    /// 是否匹配请求
    async fn matches(&self, context: &RequestContext) -> bool {
        true // 默认匹配所有请求
    }
}

/// 限流存储trait
///
/// 定义了限流数据存储的接口，支持内存和分布式存储。
#[async_trait]
pub trait RateLimitStorage: Send + Sync {
    /// 获取计数器值
    async fn get_counter(&self, key: &str) -> RateLimitResult<u64>;

    /// 增加计数器
    async fn increment_counter(
        &self,
        key: &str,
        increment: u64,
        ttl: Duration,
    ) -> RateLimitResult<u64>;

    /// 设置计数器值
    async fn set_counter(&self, key: &str, value: u64, ttl: Duration) -> RateLimitResult<()>;

    /// 删除计数器
    async fn delete_counter(&self, key: &str) -> RateLimitResult<()>;

    /// 获取过期时间
    async fn get_ttl(&self, key: &str) -> RateLimitResult<Option<Duration>>;

    /// 批量操作（可选实现）
    async fn batch_get(&self, keys: &[String]) -> RateLimitResult<Vec<u64>> {
        let mut results = Vec::new();
        for key in keys {
            let value = self.get_counter(key).await?;
            results.push(value);
        }
        Ok(results)
    }
}

/// 限流统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitStats {
    /// 总请求数
    pub total_requests: u64,
    /// 被拒绝的请求数
    pub rejected_requests: u64,
    /// 被延迟的请求数
    pub delayed_requests: u64,
    /// 拒绝率
    pub rejection_rate: f64,
    /// 平均延迟时间
    pub average_delay: Duration,
    /// 热点限流键
    pub hot_keys: Vec<(String, u64)>,
    /// 统计时间窗口
    pub window_start: SystemTime,
    pub window_end: SystemTime,
}

impl RateLimitStats {
    /// 创建新的统计信息
    pub fn new(window_start: SystemTime, window_end: SystemTime) -> Self {
        Self {
            total_requests: 0,
            rejected_requests: 0,
            delayed_requests: 0,
            rejection_rate: 0.0,
            average_delay: Duration::ZERO,
            hot_keys: Vec::new(),
            window_start,
            window_end,
        }
    }

    /// 计算拒绝率
    pub fn calculate_rejection_rate(&mut self) {
        if self.total_requests > 0 {
            self.rejection_rate = self.rejected_requests as f64 / self.total_requests as f64;
        } else {
            self.rejection_rate = 0.0; // 总请求数为0时，拒绝率为0
        }
    }
}

/// 限流器
///
/// 整合限流算法、策略和存储的主要组件。
pub struct RateLimiter {
    algorithm: Box<dyn RateLimitAlgorithm>,
    strategies: Vec<Box<dyn RateLimitStrategy>>,
    storage: Box<dyn RateLimitStorage>,
    stats: tokio::sync::RwLock<RateLimitStats>,
}

impl RateLimiter {
    /// 创建新的限流器
    pub fn new(
        algorithm: Box<dyn RateLimitAlgorithm>,
        storage: Box<dyn RateLimitStorage>,
    ) -> Self {
        let now = SystemTime::now();
        Self {
            algorithm,
            strategies: Vec::new(),
            storage,
            stats: tokio::sync::RwLock::new(RateLimitStats::new(now, now)),
        }
    }

    /// 添加限流策略
    pub fn add_strategy(mut self, strategy: Box<dyn RateLimitStrategy>) -> Self {
        self.strategies.push(strategy);
        self
    }

    /// 检查请求是否允许
    pub async fn is_allowed(&self, context: &RequestContext) -> RateLimitResult<RateLimitDecision> {
        debug!("Checking rate limit for request: {} {}", context.method, context.path);

        // 更新统计 - 增加总请求数
        {
            let mut stats = self.stats.write().await;
            stats.total_requests += 1;
            stats.calculate_rejection_rate(); // 更新拒绝率
        }

        let mut min_remaining = u32::MAX;
        let mut found_strategy = false;
        let mut final_decision: Option<RateLimitDecision> = None;

        // 遍历所有匹配的策略
        for strategy in &self.strategies {
            if !strategy.matches(context).await {
                continue;
            }

            let key = strategy.get_key(context).await;
            let config = strategy.get_config(context).await;

            if !config.enabled {
                continue;
            }

            debug!("Applying rate limit strategy: {} with key: {}", 
                   strategy.get_strategy_name(), key);

            let decision = self.algorithm.is_allowed(&key, 1, &config).await?;
            found_strategy = true;
            
            // 如果此策略拒绝了请求，立即返回拒绝
            if !decision.allowed {
                // 更新拒绝统计
                {
                    let mut stats = self.stats.write().await;
                    stats.rejected_requests += 1;
                    stats.calculate_rejection_rate();
                }

                warn!("Rate limit exceeded by strategy: {}", strategy.get_strategy_name());
                
                return Ok(decision.with_rule_id(strategy.get_strategy_name().to_string()));
            }
            
            // 记录最小的剩余配额
            min_remaining = min_remaining.min(decision.remaining);
            
            // 记录最终决策（用于返回）
            if final_decision.is_none() {
                final_decision = Some(decision.clone());
            }
            
            // 处理延迟统计
            if decision.delay.is_some() {
                let mut stats = self.stats.write().await;
                stats.delayed_requests += 1;
            }
        }

        // 如果没有找到匹配的策略，返回默认允许
        if !found_strategy {
            return Ok(RateLimitDecision::allowed(
                100,
                SystemTime::now() + Duration::from_secs(60),
            ));
        }
        
        // 所有策略都允许，返回允许决策，但使用最小的剩余配额
        let mut result = final_decision.unwrap_or_else(|| {
            RateLimitDecision::allowed(
                min_remaining,
                SystemTime::now() + Duration::from_secs(60),
            )
        });
        result.remaining = min_remaining;
        
        Ok(result)
    }

    /// 获取统计信息
    pub async fn get_stats(&self) -> RateLimitStats {
        self.stats.read().await.clone()
    }

    /// 重置统计信息
    pub async fn reset_stats(&self) {
        let mut stats = self.stats.write().await;
        let now = SystemTime::now();
        *stats = RateLimitStats::new(now, now);
    }

    /// 获取剩余配额
    pub async fn get_remaining(&self, context: &RequestContext) -> RateLimitResult<Vec<(String, u32)>> {
        let mut results = Vec::new();

        for strategy in &self.strategies {
            if strategy.matches(context).await {
                let key = strategy.get_key(context).await;
                let config = strategy.get_config(context).await;
                
                if config.enabled {
                    let remaining = self.algorithm.get_remaining(&key, &config).await?;
                    results.push((strategy.get_strategy_name().to_string(), remaining));
                }
            }
        }

        Ok(results)
    }
}

// 重新导出子模块
pub use algorithms::*;
pub use strategies::*;
pub use storage::*;
pub use middleware::*;

// 引入新的核心接口
use crate::core::{
    Middleware as CoreMiddleware, GatewayRequest, GatewayResponse, GatewayContext, 
    GatewayResult, GatewayError, RateLimitInfo
};
use std::sync::Arc;

/// 限流中间件适配器，将现有的RateLimiter适配到新的Middleware接口
pub struct RateLimiterMiddleware {
    limiter: Arc<RateLimiter>,
    name: String,
    priority: i32,
}

impl RateLimiterMiddleware {
    pub fn new(limiter: Arc<RateLimiter>) -> Self {
        Self {
            limiter,
            name: "RateLimiter".to_string(),
            priority: 15, // 限流通常在认证后执行
        }
    }
    
    pub fn with_name(mut self, name: String) -> Self {
        self.name = name;
        self
    }
    
    pub fn with_priority(mut self, priority: i32) -> Self {
        self.priority = priority;
        self
    }
    
    /// 从网关请求创建限流上下文
    fn create_rate_limit_context(&self, request: &GatewayRequest) -> RequestContext {
        let mut context = RequestContext::new(request.path.clone(), request.method.to_string());
        
        // 设置客户端IP
        if let Some(client_ip) = &request.client_ip {
            if let Ok(ip) = client_ip.parse() {
                context = context.with_client_ip(ip);
            }
        }
        
        // 设置目标服务
        if let Some(service) = &request.target_service {
            context = context.with_service(service.clone());
        }
        
        // 设置API Key（从请求头获取）
        if let Some(api_key) = request.headers.get("x-api-key") {
            if let Ok(api_key_str) = api_key.to_str() {
                context = context.with_api_key(api_key_str.to_string());
            }
        }
        
        // 设置查询参数
        context.query_params = request.query_params.clone();
        context.headers = request.headers.clone();
        
        context
    }
    
    /// 从限流决策创建限流信息
    fn create_rate_limit_info(&self, decision: &RateLimitDecision, rule_id: Option<String>) -> RateLimitInfo {
        RateLimitInfo {
            limited: !decision.allowed,
            remaining: decision.remaining,
            reset_time: decision.reset_time,
            rule_id,
        }
    }
}

#[async_trait]
impl CoreMiddleware for RateLimiterMiddleware {
    async fn before_request(&self, request: GatewayRequest, mut context: Arc<GatewayContext>) -> GatewayResult<GatewayRequest> {
        // 创建限流上下文
        let rate_limit_context = self.create_rate_limit_context(&request);
        
        // 执行限流检查
        let decision = self.limiter.is_allowed(&rate_limit_context).await
            .map_err(|e| {
                match e {
                    RateLimitError::LimitExceeded => {
                        GatewayError::rate_limit("超出限流限制")
                    },
                    RateLimitError::StorageError(msg) => {
                        GatewayError::internal(format!("限流存储错误: {}", msg))
                    },
                    RateLimitError::ConfigError(msg) => {
                        GatewayError::configuration(format!("限流配置错误: {}", msg))
                    },
                    RateLimitError::InternalError(msg) => {
                        GatewayError::internal(format!("限流内部错误: {}", msg))
                    }
                }
            })?;
        
        // 如果请求被拒绝，返回限流错误
        if !decision.allowed {
            let retry_after = decision.reset_time
                .duration_since(SystemTime::now())
                .unwrap_or(Duration::from_secs(60))
                .as_secs();
                
            let mut error = GatewayError::rate_limit("请求频率过高，请稍后重试");
            if let GatewayError::RateLimit { retry_after: ref mut retry, .. } = error {
                *retry = Some(retry_after);
            }
            
            return Err(error);
        }
        
        // 如果有延迟要求，这里可以实现延迟逻辑
        if let Some(delay) = decision.delay {
            if !delay.is_zero() {
                tokio::time::sleep(delay).await;
            }
        }
        
        // 将限流信息添加到上下文
        // 注意：由于Arc<T>的不可变性，这里需要更复杂的处理
        // 在实际实现中，可能需要使用RefCell或其他方式来修改context
        let rate_limit_info = self.create_rate_limit_info(&decision, decision.rule_id.clone());
        
        Ok(request)
    }
    
    async fn after_response(&self, mut response: GatewayResponse, context: Arc<GatewayContext>) -> GatewayResult<GatewayResponse> {
        // 在响应头中添加限流信息
        if let Some(rate_limit_info) = &context.rate_limit_info {
            response.add_header("X-RateLimit-Remaining", &rate_limit_info.remaining.to_string());
            
            if let Ok(reset_time) = rate_limit_info.reset_time
                .duration_since(SystemTime::UNIX_EPOCH) {
                response.add_header("X-RateLimit-Reset", &reset_time.as_secs().to_string());
            }
            
            if let Some(rule_id) = &rate_limit_info.rule_id {
                response.add_header("X-RateLimit-Rule", rule_id);
            }
        }
        
        Ok(response)
    }
    
    fn name(&self) -> &str {
        &self.name
    }
    
    fn priority(&self) -> i32 {
        self.priority
    }
}

#[cfg(test)]
mod middleware_tests {
    use super::*;
    use crate::core::{GatewayRequest, GatewayContext};
    use axum::http::{Method, Uri, HeaderMap, HeaderValue, StatusCode};
    use std::sync::Arc;
    use tokio;
    use std::time::Duration;

    // ==================== Mock 实现 ====================
    
    /// Mock 限流算法，用于测试
    pub struct MockRateLimitAlgorithm {
        pub should_allow: bool,
        pub remaining: u32,
        pub should_error: bool,
        pub delay: Option<Duration>,
        pub call_count: Arc<std::sync::Mutex<u32>>,
    }
    
    impl MockRateLimitAlgorithm {
        pub fn new() -> Self {
            Self {
                should_allow: true,
                remaining: 100,
                should_error: false,
                delay: None,
                call_count: Arc::new(std::sync::Mutex::new(0)),
            }
        }
        
        pub fn with_reject(mut self) -> Self {
            self.should_allow = false;
            self.remaining = 0;
            self
        }
        
        pub fn with_error(mut self) -> Self {
            self.should_error = true;
            self
        }
        
        pub fn with_delay(mut self, delay: Duration) -> Self {
            self.delay = Some(delay);
            self
        }
        
        pub fn with_remaining(mut self, remaining: u32) -> Self {
            self.remaining = remaining;
            self
        }
        
        pub fn get_call_count(&self) -> u32 {
            *self.call_count.lock().unwrap()
        }
    }
    
    #[async_trait]
    impl RateLimitAlgorithm for MockRateLimitAlgorithm {
        async fn is_allowed(&self, _key: &str, _tokens: u32, _config: &RateLimitConfig) -> RateLimitResult<RateLimitDecision> {
            // 增加调用计数
            {
                let mut count = self.call_count.lock().unwrap();
                *count += 1;
            }
            
            if self.should_error {
                return Err(RateLimitError::InternalError("Mock algorithm error".to_string()));
            }
            
            let decision = RateLimitDecision {
                allowed: self.should_allow,
                remaining: self.remaining,
                reset_time: SystemTime::now() + Duration::from_secs(60),
                delay: self.delay,
                reason: if self.should_allow { None } else { Some("Rate limit exceeded".to_string()) },
                rule_id: Some("mock_rule".to_string()),
            };
            
            Ok(decision)
        }
        
        async fn get_remaining(&self, _key: &str, _config: &RateLimitConfig) -> RateLimitResult<u32> {
            Ok(self.remaining)
        }
        
        async fn reset(&self, _key: &str) -> RateLimitResult<()> {
            Ok(())
        }
        
        fn get_algorithm_type(&self) -> RateLimitAlgorithmType {
            RateLimitAlgorithmType::TokenBucket
        }
        
        fn get_algorithm_name(&self) -> &str {
            "mock_algorithm"
        }
    }
    
    /// Mock 限流策略，用于测试
    pub struct MockRateLimitStrategy {
        pub should_match: bool,
        pub key: String,
        pub config: RateLimitConfig,
        pub strategy_name: String,
    }
    
    impl MockRateLimitStrategy {
        pub fn new() -> Self {
            Self {
                should_match: true,
                key: "test_key".to_string(),
                config: RateLimitConfig {
                    algorithm: RateLimitAlgorithmType::TokenBucket,
                    max_requests: 100,
                    window_duration: Duration::from_secs(60),
                    burst_capacity: Some(100),
                    refill_rate: Some(1),
                    enabled: true,
                    block_behavior: BlockBehavior::Reject,
                    custom_params: HashMap::new(),
                },
                strategy_name: "mock_strategy".to_string(),
            }
        }
        
        pub fn with_no_match(mut self) -> Self {
            self.should_match = false;
            self
        }
        
        pub fn with_key(mut self, key: String) -> Self {
            self.key = key;
            self
        }
        
        pub fn with_disabled(mut self) -> Self {
            self.config.enabled = false;
            self
        }
    }
    
    #[async_trait]
    impl RateLimitStrategy for MockRateLimitStrategy {
        async fn matches(&self, _context: &RequestContext) -> bool {
            self.should_match
        }
        
        async fn get_key(&self, _context: &RequestContext) -> String {
            self.key.clone()
        }
        
        async fn get_config(&self, _context: &RequestContext) -> RateLimitConfig {
            self.config.clone()
        }
        
        fn get_strategy_type(&self) -> RateLimitStrategyType {
            RateLimitStrategyType::Custom("mock".to_string())
        }
        
        fn get_strategy_name(&self) -> &str {
            &self.strategy_name
        }
    }
    
    // ==================== 测试工具函数 ====================
    
    /// 创建测试用的GatewayRequest
    fn create_test_request(method: Method, path: &str) -> GatewayRequest {
        let uri: Uri = path.parse().unwrap_or_else(|_| Uri::from_static("/"));
        let mut request = GatewayRequest::new(method, uri);
        request.path = path.to_string();
        request.set_target_service("test-service".to_string());
        request.set_client_ip("192.168.1.100".to_string());
        request
    }
    
    /// 创建带有API Key的测试请求
    fn create_test_request_with_api_key(method: Method, path: &str, api_key: &str) -> GatewayRequest {
        let mut request = create_test_request(method, path);
        request.add_header("x-api-key", api_key);
        request
    }
    
    /// 创建测试用的GatewayContext
    fn create_test_context() -> Arc<GatewayContext> {
        Arc::new(GatewayContext {
            request_id: "test-request-123".to_string(),
            auth_info: None,
            rate_limit_info: None,
            route_info: None,
            attributes: std::collections::HashMap::new(),
            start_time: SystemTime::now(),
        })
    }
    
    /// 创建测试用的RateLimiter
    fn create_test_rate_limiter(algorithm: Box<dyn RateLimitAlgorithm>, strategies: Vec<Box<dyn RateLimitStrategy>>) -> RateLimiter {
        RateLimiter {
            algorithm,
            strategies,
            storage: Box::new(MemoryStorage::new()),
            stats: tokio::sync::RwLock::new(RateLimitStats::new(
                SystemTime::now(),
                SystemTime::now()
            )),
        }
    }
    
    // ==================== RateLimiterMiddleware 基础测试 ====================
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_creation() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new());
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        assert_eq!(middleware.name(), "RateLimiter");
        assert_eq!(middleware.priority(), 15);
    }
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_with_custom_name() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new());
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter)
            .with_name("CustomRateLimiter".to_string())
            .with_priority(20);
        
        assert_eq!(middleware.name(), "CustomRateLimiter");
        assert_eq!(middleware.priority(), 20);
    }
    
    // ==================== 限流允许测试 ====================
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_allows_request() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new().with_remaining(50));
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        let request = create_test_request(Method::GET, "/api/users");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok(), "Request should be allowed when under rate limit");
    }
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_rejects_request() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new().with_reject());
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        let request = create_test_request(Method::GET, "/api/users");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_err(), "Request should be rejected when rate limit exceeded");
        
        let error = result.unwrap_err();
        assert!(matches!(error, crate::core::GatewayError::RateLimit { .. }));
    }
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_with_delay() {
        let start_time = std::time::Instant::now();
        let algorithm = Box::new(MockRateLimitAlgorithm::new().with_delay(Duration::from_millis(50)));
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        let request = create_test_request(Method::GET, "/api/users");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        let elapsed = start_time.elapsed();
        
        assert!(result.is_ok(), "Request should be allowed with delay");
        assert!(elapsed >= Duration::from_millis(40), "Should have delayed for at least 40ms");
    }
    
    // ==================== 错误处理测试 ====================
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_internal_error() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new().with_error());
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        let request = create_test_request(Method::GET, "/api/users");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_err(), "Internal error should be propagated");
        
        let error = result.unwrap_err();
        assert!(matches!(error, crate::core::GatewayError::Internal { .. }));
    }
    
    // ==================== 上下文创建测试 ====================
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_create_context() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new());
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        let mut request = create_test_request_with_api_key(Method::POST, "/api/orders", "sk_test_123");
        request.query_params.insert("filter".to_string(), "active".to_string());
        
        let rate_limit_context = middleware.create_rate_limit_context(&request);
        
        assert_eq!(rate_limit_context.path, "/api/orders");
        assert_eq!(rate_limit_context.method, "POST");
        assert_eq!(rate_limit_context.service, Some("test-service".to_string()));
        assert_eq!(rate_limit_context.client_ip, Some("192.168.1.100".parse().unwrap()));
        assert_eq!(rate_limit_context.api_key, Some("sk_test_123".to_string()));
        assert_eq!(rate_limit_context.query_params.get("filter"), Some(&"active".to_string()));
    }
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_create_rate_limit_info() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new());
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        let reset_time = SystemTime::now() + Duration::from_secs(3600);
        let decision = RateLimitDecision {
            allowed: true,
            remaining: 75,
            reset_time,
            delay: None,
            reason: None,
            rule_id: Some("test_rule_123".to_string()),
        };
        
        let rate_limit_info = middleware.create_rate_limit_info(&decision, Some("custom_rule".to_string()));
        
        assert!(!rate_limit_info.limited);
        assert_eq!(rate_limit_info.remaining, 75);
        assert_eq!(rate_limit_info.reset_time, reset_time);
        assert_eq!(rate_limit_info.rule_id, Some("custom_rule".to_string()));
    }
    
    // ==================== 响应处理测试 ====================
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_after_response() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new());
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        let response = crate::core::GatewayResponse::new(StatusCode::OK);
        
        // 模拟上下文中的限流信息
        let rate_limit_info = crate::core::RateLimitInfo {
            limited: false,
            remaining: 42,
            reset_time: SystemTime::now() + Duration::from_secs(3600),
            rule_id: Some("test_rule".to_string()),
        };
        
        let context_with_info = Arc::new(GatewayContext {
            request_id: "test-request-123".to_string(),
            auth_info: None,
            rate_limit_info: Some(rate_limit_info),
            route_info: None,
            attributes: std::collections::HashMap::new(),
            start_time: SystemTime::now(),
        });
        
        let result = middleware.after_response(response, context_with_info).await;
        assert!(result.is_ok());
        
        let processed_response = result.unwrap();
        // 验证响应头是否添加了限流信息
        assert!(processed_response.headers.contains_key("x-ratelimit-remaining"));
        assert!(processed_response.headers.contains_key("x-ratelimit-reset"));
        assert!(processed_response.headers.contains_key("x-ratelimit-rule"));
    }
    
    // ==================== 无匹配策略测试 ====================
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_no_matching_strategy() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new());
        let strategies = vec![Box::new(MockRateLimitStrategy::new().with_no_match()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        let request = create_test_request(Method::GET, "/api/users");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok(), "Request should be allowed when no strategy matches");
    }
    
    // ==================== 禁用策略测试 ====================
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_disabled_strategy() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new().with_reject()); // 算法会拒绝，但策略被禁用
        let strategies = vec![Box::new(MockRateLimitStrategy::new().with_disabled()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        let request = create_test_request(Method::GET, "/api/users");
        let context = create_test_context();
        
        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok(), "Request should be allowed when strategy is disabled");
    }
    
    // ==================== 边界条件测试 ====================
    
    #[tokio::test]
    async fn test_rate_limiter_middleware_edge_cases() {
        let algorithm = Box::new(MockRateLimitAlgorithm::new());
        let strategies = vec![Box::new(MockRateLimitStrategy::new()) as Box<dyn RateLimitStrategy>];
        let limiter = Arc::new(create_test_rate_limiter(algorithm, strategies));
        let middleware = RateLimiterMiddleware::new(limiter);
        
        // 测试空路径
        let request1 = create_test_request(Method::GET, "");
        let context1 = create_test_context();
        let result1 = middleware.before_request(request1, context1).await;
        assert!(result1.is_ok(), "Empty path should be handled");
        
        // 测试无效IP格式
        let mut request2 = create_test_request(Method::GET, "/api/test");
        request2.client_ip = Some("invalid-ip".to_string());
        let context2 = create_test_context();
        let result2 = middleware.before_request(request2, context2).await;
        assert!(result2.is_ok(), "Invalid IP format should be handled gracefully");
        
        // 测试特殊字符路径
        let request3 = create_test_request(Method::GET, "/api/用户/测试");
        let context3 = create_test_context();
        let result3 = middleware.before_request(request3, context3).await;
        assert!(result3.is_ok(), "Unicode paths should be handled");
    }
}